<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>图书列表</title>
  <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.27.2/axios.min.js"></script>
  <script src="https://cdn.bootcdn.net/ajax/libs/art-template/4.13.2/lib/template-web.js"></script>
</head>
<body>
  <h2>图书列表</h2>

  <button onclick="window.location='./add.html'">添加</button>
  <ul>
  </ul>

  <script id="lis" type="text/html">
    <%
      books.forEach(b => {
    %>
      <li>
        <%=b._id%>--<%=b.name%>--<%=b.author%>--<%=b.price%>
        <button onclick="window.location='./update.html?id=<%=b._id%>'">修改</button>
        <button onclick="delBook('<%=b._id%>')">删除</button>
      </li>
    <%
      })
    %>
  </script>

  <script>
    // 请求获取图书列表并渲染成列表
    async function getBooks() {
      // const response = await axios('http://localhost:8080/book');
      const response = await axios.get('http://localhost:8080/book');
      const books = response.data.data
      // 渲染模板, 生成标签字符串
      const html = template('lis', {books: books})
      // 插入到ul中
      document.querySelector('ul').innerHTML = html
    }
    getBooks()

    // 点击删除指定图书
    async function delBook(id) {
      // 请求删除的接口
      // await axios({
      //   url: 'http://localhost:8080/book',
      //   method: 'delete',
      //   params: {
      //     id
      //   }
      // })
      await axios.delete('http://localhost:8080/book', {params: {id}})
      
      // 成功后, 跳转到/books.html
      window.location = './books.html'
    }
  </script>
</body>
</html>